package cuongnh.project.japanesediary.vocabulary.ui.view.action.menucontribution.vocabulary.grammars;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;

import cuongnh.project.japanesediary.vocabulary.common.CommonServices;
import cuongnh.project.japanesediary.vocabulary.model.Vocabulary;
import cuongnh.project.japanesediary.vocabulary.model.Grammar;
import cuongnh.project.japanesediary.vocabulary.ui.view.VocabularyGrammarsView;

public class RemoveVocabularyGrammarAction implements IViewActionDelegate {

	public static final String ID = "cuongnh.project.japanesediary.vocabulary.action.RemoveVocabularyGrammar";

	protected IViewPart m_view;

	private CommonServices commonServices;

	private Vocabulary vocabulary;

	private Grammar selectedGrammar;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.IViewActionDelegate#init(org.eclipse.ui.IViewPart)
	 */
	@Override
	public void init(IViewPart view) {
		m_view = view;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
	 */
	@Override
	public void run(IAction action) {
		// 履歴ビュー更新
		VocabularyGrammarsView view = (VocabularyGrammarsView) m_view
				.getAdapter(VocabularyGrammarsView.class);
		commonServices = view.getCommonServices();
		vocabulary = view.getCurrentVocabulary();
		selectedGrammar = view.getSelection();
		if (selectedGrammar != null) {
			boolean confirm = MessageDialog
					.openConfirm(view.getSite().getShell(),
							"Deleting confirmation!",
							"Are you sure you want to delete this Grammar from current Vocabulary?");
			if (confirm) {
				// remove selected vocabulary to current vocabulary
				Vocabulary currentVocabulary = commonServices.getVocabularyDao()
						.getVocabularyWithGrammars(vocabulary.getVocabularyId());
				currentVocabulary.getGrammars().remove(selectedGrammar);
				commonServices.getVocabularyDao().update(currentVocabulary);

				// remove current vocabulary for selected vocabulary
				selectedGrammar = commonServices.getGrammarDao()
						.getGrammarWithVocabularies(
								selectedGrammar.getGrammarId());
				selectedGrammar.getVocabularies().remove(currentVocabulary);
				commonServices.getGrammarDao().update(selectedGrammar);
				view.update();
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action
	 * .IAction, org.eclipse.jface.viewers.ISelection)
	 */
	@Override
	public void selectionChanged(IAction action, ISelection selection) {

	}

}
